<template>
  <div ref="signatureBox" class="signatureBox" @touchmove.prevent>
    <canvas id="canvas" ref="myCanvas" :width="getBoundingClientRect.width" :height="getBoundingClientRect.height" @mousedown="canvasDown($event)" @mousemove="canvasMove($event)" @mouseup="canvasUp()" @mouseleave="canvasLeave()">抱歉，您的浏览器不支持canvas元素</canvas>
  </div>
</template>

<script lang="ts">
import { ref, reactive, onMounted } from 'vue'
export default {
  emits: ['setImg'],
  setup(props, { emit }) {
    const myCanvas = ref<any>(null)
    interface dataType {
      ctx: any
      canvasMoveUse: boolean
      imgSrc: string
    }
    const data = reactive({
      ctx: null,
      canvasMoveUse: false,
      imgSrc: ''
    } as dataType)
    const clear = () => {
      data.ctx.clearRect(0, 0, data.ctx.canvas.width, data.ctx.canvas.height)
      data.imgSrc = ''
    }
    const ok = () => {
      console.log(myCanvas.value)
      const base64Img = myCanvas.value.toDataURL('image/jpg')
      data.imgSrc = base64Img
      emit('setImg', data.imgSrc)
    }
    const canvasDown = (e) => {
      data.canvasMoveUse = true
      const canvasX = e.offsetX
      const canvasY = e.offsetY
      data.ctx.beginPath() // 移动的起点
      data.ctx.moveTo(canvasX, canvasY)
    }
    const canvasMove = (e) => {
      if (data.canvasMoveUse) {
        const canvasX = e.offsetX
        const canvasY = e.offsetY
        data.ctx.lineTo(canvasX, canvasY)
        data.ctx.stroke()
      }
    }
    const canvasUp = () => {
      data.canvasMoveUse = false
    }
    const canvasLeave = () => {
      data.canvasMoveUse = false
    }
    const signatureBox = ref<any>(null)
    const getBoundingClientRect = reactive({ height: 0, width: 0 })
    onMounted(() => {
      getBoundingClientRect.height = signatureBox.value.getBoundingClientRect().height - 14
      getBoundingClientRect.width = signatureBox.value.getBoundingClientRect().width - 14
      data.ctx = myCanvas.value.getContext('2d')
      data.ctx.lineWidth = 5
    })
    return {
      signatureBox,
      getBoundingClientRect,
      myCanvas,
      clear,
      ok,
      canvasDown,
      canvasMove,
      canvasUp,
      canvasLeave
    }
  }
}
</script>

<style lang="scss" scoped>
.signatureBox {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}
#canvas {
  border: 1px solid #56b6ff;
  border-radius: 6px;
}
</style>
